import java.util.Arrays;

public class Heap {
    int[] elem;
    int usedSize;

    public void initHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    Heap() {
        elem = new int[10];
        usedSize = 0;
    }

    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize - 1);
        }
    }

    public void siftDown(int parent, int len) {
        int child = parent * 2 + 1;
        while (child <= len) {
            if (child + 1 <= len && elem[child + 1] > elem[child]) {
                child++;
            }
            if (elem[parent] < elem[child]) {
                swap(child, parent);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public int poll() {
        if(isEmpty()) {
            return -1;
        }
        int oldVal = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize-1);
        return oldVal;
    }

    public void siftUp(int child) {
        int parent = (child-1)/2;
        while(parent>=0) {
            if(elem[parent]<elem[child]) {
                swap(parent, child);
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }

    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize-1);
    }

    public void swap(int a, int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }

    public int peek() {
        if (isEmpty()) {
            return -1;
        }
        return elem[0];
    }

    public void print() {
        System.out.println(Arrays.toString(elem));
    }

    boolean isEmpty() {
        return usedSize == 0;
    }

    boolean isFull() {
        return usedSize == elem.length;
    }

    public void HeapSort() {
        int end = usedSize-1;
        while(end>=0) {
            swap(0,end);
            end--;
            siftDown(0,end);
        }
        print();
    }
}
